package com.fs.system.service.impl;
import com.fs.common.core.vo.LoginUser;
import com.fs.system.service.LoginService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.time.Duration;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

public class LoginServiceImpl implements LoginService {
    @Autowired
    private RedisTemplate<String, LoginUser> redisTemplate;

    private final String PREFIX = "prefix:";

    /**
     * 生成jwtToken方法
     * @param loginUser
     * @return
     */
    @Override
    public String generateToken(LoginUser loginUser) {
        String uuid = UUID.randomUUID().toString();
        String compact = Jwts.builder()
                .setSubject("LOGIN")
                .claim("uuid", uuid)
                .signWith(SignatureAlgorithm.HS256, "HUSE")
                .compact();
        loginUser.setToken(uuid);
        String redisKey = PREFIX + uuid;
        //token保存到Redis，在Redis中设置有效期，有效期一到，Redis自动删除  这里我llb设置过期时间为30分钟
        redisTemplate.opsForValue().set(redisKey, loginUser, Duration.ofMinutes(30));
        return compact;//把jwt我返回出去
    }

    /**
     * 更新Token方法
     * @param jwt
     */
    @Override
    public void updateToken(String jwt) {
        Claims claims = Jwts.parser()
                .setSigningKey("HUSE")
                .parseClaimsJws(jwt)
                .getBody();
        String uuid = claims.get("uuid", String.class);
        String redisKey = PREFIX + uuid;//按照要求，redis的key存前缀+uuid
        redisTemplate.expire(redisKey, Duration.ofMinutes(30));
//        System.out.println(builder.compact());
    }

    /**
     * 解析用户信息从->Jwt中
     * @param jwt
     */
    @Override
    public LoginUser parserUserInfoByJwt(String jwt) {
        Claims claims = Jwts.parser()
                .setSigningKey("HUSE")
                .parseClaimsJws(jwt)
                .getBody();
        String uuid = claims.get("uuid", String.class);
        String redisKey = PREFIX + uuid;
//        System.out.println(redisKey);
//        System.out.println(redisKey2);
//        System.out.println(redisKey3);
//        System.out.println(redisKey4);
        return redisTemplate.opsForValue().get(redisKey);//实现延期
    }

    /**
     * 将LoginUser保存到Redis中
     * @param loginUser
     */
    @Override
    public void saveToRedis(LoginUser loginUser) {
        String uuid = loginUser.getToken();
        String redisKey = PREFIX + uuid;
        redisTemplate.opsForValue().set(redisKey, loginUser, Duration.ofMinutes(30));
    }
}

